<template>
    <div class="exam-edit-container">
      <el-card class="box-card">
        <div slot="header" class="clearfix">
          <span>{{ id ? '编辑试卷' : '新增试卷' }}</span>
          <el-button  style="float: right; margin-left: 10px"  type="primary" @click="submitForm" :loading="submitting">保存</el-button>
          <el-button  style="float: right" @click="cancelEdit">取消</el-button>
        </div>

        <el-form  ref="examForm" :model="form"  :rules="rules" label-width="100px">
          <!-- 基本信息 -->
          <el-form-item label="试卷名称" prop="name">
            <el-input v-model="form.name" placeholder="请输入试卷名称"></el-input>
          </el-form-item>  
          <el-form-item label="考试时长" prop="timeLimit">
            <el-input-number v-model="form.timeLimit" :min="10" :max="300" controls-position="right"></el-input-number>
            <span style="margin-left: 10px">分钟</span>
          </el-form-item>
          <el-form-item label="总分" prop="totalScore">
            <el-input-number  v-model="form.totalScore" :min="1"  :max="200" controls-position="right"></el-input-number>
          </el-form-item>
          <el-form-item label="试卷状态" prop="status">
            <el-radio-group v-model="form.status">
              <el-radio label="draft">草稿</el-radio>
              <el-radio label="published" :disabled="!id">已发布</el-radio>
              <el-radio label="archived">已归档</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="考试时间" v-if="form.status === 'published'">
            <el-date-picker v-model="timeRange" type="datetimerange" range-separator="至" start-placeholder="开始时间" end-placeholder="结束时间"
            value-format="yyyy-MM-dd HH:mm:ss"></el-date-picker>
          </el-form-item>  
          <el-form-item label="试卷描述" prop="description">
            <el-input v-model="form.description" type="textarea" :rows="3" placeholder="请输入试卷描述"></el-input>
          </el-form-item>
          <!-- 题目列表 -->
          <el-form-item label="题目列表" prop="questions">
            <div class="question-list">
              <div v-for="(question, index) in form.questions" :key="question.id" class="question-item">
                <div class="question-header">
                  <span class="question-title">题目 {{ index + 1 }}: {{ question.content }}</span>
                  <div class="question-actions">
                    <el-input-number v-model="question.score" :min="1" :max="100" size="mini" style="width: 100px; margin-right: 10px;"></el-input-number>
                    <el-button type="danger" size="mini" icon="el-icon-delete" circle @click="removeQuestion(index)"></el-button>
                  </div>
                </div>
                <div class="question-meta">
                  <span>类型: {{ questionTypeText[question.type] }}</span>
                  <span>难度: 
                    <el-rate v-model="question.difficulty" disabled :max="5" style="display: inline-block;"></el-rate>
                  </span>
                </div>
              </div>
              <el-button type="primary" plain icon="el-icon-plus" @click="showQuestionSelector">添加题目</el-button>
            </div>
          </el-form-item>
        </el-form>
      </el-card>
      
      <!-- 题目选择器对话框 -->
      <el-dialog title="选择题目" :visible.sync="questionDialogVisible" width="80%" top="5vh">
        <question-selector 
          ref="questionSelector"
          :selected-questions="form.questions"
          @confirm="handleQuestionsSelected"
          @cancel="questionDialogVisible = false"
        ></question-selector>
      </el-dialog>
    </div>
  </template>
  
  <script>
  import { getExamDetail, saveExam } from '@/api/study-exam'
  import QuestionSelector from '@/components/QuestionSelector'
  
  export default {
    name: 'ExamEdit',
    components: { QuestionSelector },
    data() {
      return {
        id: '',
        submitting: false,
        questionDialogVisible: false,
        questionTypeText: {
          single: '单选题',
          multiple: '多选题',
          judgment: '判断题'
        },
        timeRange: [],
        form: {
          name: '',
          timeLimit: 120,
          totalScore: 100,
          status: 'draft',
          startTime: null,
          endTime: null,
          description: '',
          questions: []
        },
        rules: {
          name: [{ required: true, message: '请输入试卷名称', trigger: 'blur' }],
          timeLimit: [{ required: true, message: '请输入考试时长', trigger: 'blur' }],
          totalScore: [{ required: true, message: '请输入总分', trigger: 'blur' }],
          status: [{ required: true, message: '请选择状态', trigger: 'change' }],
          questions: [
            { 
              validator: this.validateQuestions, 
              trigger: 'change' 
            }
          ]
        }
      }
    },
    computed: {
      calculatedTotalScore() {
        return this.form.questions.reduce((sum, q) => sum + (q.score || 0), 0)
      }
    },
    watch: {
      calculatedTotalScore(newVal) {
        this.form.totalScore = newVal
      },
      timeRange(val) {
        if (val && val.length === 2) {
          this.form.startTime = val[0]
          this.form.endTime = val[1]
        } else {
          this.form.startTime = null
          this.form.endTime = null
        }
      }
    },
    created() {
      var id = this.$route.params.id;
      this.id = id;
      if (this.id) {
        this.fetchExamDetail()
      }
    },
    methods: {
      // 获取试卷详情
      fetchExamDetail() {
        getExamDetail(this.id).then(response => {
          const data = response.data
          this.form = {
            id: data.id,
            name: data.name,
            timeLimit: data.timeLimit,
            totalScore: data.totalScore,
            status: data.status,
            startTime: data.startTime,
            endTime: data.endTime,
            description: data.description,
            questions: data.questions || []
          }
          if (data.startTime && data.endTime) {
            this.timeRange = [data.startTime, data.endTime]
          }
        }).catch(error => {
          console.error('获取试卷详情失败:', error)
          this.$message.error('获取试卷详情失败')
        })
      },
      
      // 显示题目选择器
      showQuestionSelector() {
        this.questionDialogVisible = true
        this.$nextTick(() => {
          this.$refs.questionSelector.refreshList()
        })
      },
      
      // 处理选择的题目
      handleQuestionsSelected(questions) {
        this.form.questions = questions
        this.questionDialogVisible = false
        // 自动计算总分
        this.form.totalScore = this.calculatedTotalScore
      },
      
      // 移除题目
      removeQuestion(index) {
        this.form.questions.splice(index, 1)
        this.form.totalScore = this.calculatedTotalScore
      },
      
      // 验证题目列表
      validateQuestions(rule, value, callback) {
        if (this.form.questions.length === 0) {
          callback(new Error('请至少添加一个题目'))
          return
        }
        callback()
      },
      
      // 提交表单
      async submitForm() {
        this.$refs.examForm.validate(valid => {
          if (!valid) {
            return this.$message.warning('请完善试卷信息')
          }
          try{
            const formData = { 
              ...this.form,
            }
            saveExam(formData)
            this.$message.success('题目保存成功')
            this.$router.push('/study/exam/list')
          }catch(error) {
            console.error('保存试卷失败:', error)
            this.$message.error('保存试卷失败: ' + (error.message || '服务器错误'))
          } finally{
            
          }
        })
      },

      cancelEdit() {
        this.$router.push('/study/exam/list')
      }
    }
}
    </script>